import { reqGetUserDetailById, reqGetUserInfo, reqLogin } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    // 把token存到vuex
    state.token = newToken
    // 把token存到cookie
    setToken(newToken)
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  // 清除token
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  // 清除用户基本资料
  removeUserInfo(state) {
    state.userInfo = ''
  }
}
const actions = {
  // 登录
  async login(context, loginForm) {
    const res = await reqLogin(loginForm)
    console.log(res)
    const token = res.data
    context.commit('setToken', token)
  },
  // 获取用户基本资料
  async getUserInfo({ commit }) {
    const { data: data1 } = await reqGetUserInfo()
    // console.log(data)
    const { data: data2 } = await reqGetUserDetailById(data1.userId)
    // 合并对象
    // const res = { ...data1, ...data2 }
    const res = Object.assign(data1, data2)
    commit('setUserInfo', res)
    return res
  },
  // 退出功能
  loyout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  }

}

export default {
  state,
  mutations,
  actions,
  namespaced: true
}
